import os.path
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from openpyxl import Workbook, load_workbook

import student


class QmyWidget(QWidget):
    numberSignal = pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = student.Ui_Form()
        self.ui.setupUi(self)
        self.__student = dict()
        self.numberSignal.connect(self.isNumberExisting)

    @pyqtSlot()
    def scoreCalculate(self):
        s = self.ui.chinese.value() + self.ui.math.value() + self.ui.english.value()
        self.ui.total.setText(str(s))
        template = "{:.1f}".format(s / 3)
        self.ui.average.setText(template)

        self.__count += 1
        temp = list()
        temp.append(self.__count)
        temp.append(self.ui.chinese.value())
        temp.append(self.ui.math.value())
        temp.append(self.ui.english.value())
        temp.append(s)
        temp.append(float(template))
        self.__score.append(temp)

    @pyqtSlot()
    def on_btnSave_clicked(self):
        path = "D:\\StudyPython\\Project1\\student.xlsx"
        if os.path.exists(path):
            wbook = load_workbook(path)
        else:
            wbook = Workbook()
        wsheet = wbook.active
        wsheet.append(["姓名", "学号", "语文", "数学", "英语", "总成绩", "平均分"])
        student_number = self.__student.keys()
        student_number = list(student_number)
        student_number.sort()
        for i in student_number:
            wsheet.append(self.__student[i])
        wbook.save(path)

    def isNumberExisting(self, value):
        if value is self.__student:
            existing = QMessageBox.question(self, "确认信息", "该学号已经存在，是否覆盖？", QMessageBox.Yes | QMessageBox.No)
            if existing == QMessageBox.No:
                self.ui.number.setValue(0)

    def on_number_editingFinished(self):
        self.numberSignal.emit(self.ui.number.value())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    MainWindow = QmyWidget()
    MainWindow.show()
    n = app.exec()
    sys.exit(n)
